<template>
<section>
  <el-row>
      <!--工具条-->
      <el-col :span="6" class="toolbar roles">
          <el-card class="box-card">
              <template #header>
                  <div class="clearfix">
                      <span>设备组</span>
                  </div>
              </template>
              <div class="block">
                <el-input
                    v-model="filterText"
                    placeholder="搜索"
                  />
                  <el-tree
                    :data="treeData"
                    class="filter-tree"
                    node-key="value"
                    :props="defaultProps"
                    ref="treeRef"
                    default-expand-all
                    :expand-on-click-node="true"
                    :check-strictly="true"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
                  >
                  </el-tree>
              </div>
          </el-card>

      </el-col>
      <el-col :span="18" class="toolbar perms morechildren">
          <el-card class="box-card">
              <template #header>
                  <div class="clearfix">
                      <span>变量列表</span> 
                  </div>
              </template>
              <div class="block">
                <el-form :inline="true" @submit.native.prevent>
                    <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="请输入搜索内容"></el-input>
                    </el-form-item>
                    <el-form-item>
                    <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                    <el-form-item v-if="buttonFuncs.handleAdd">
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                    </el-form-item>
                </el-form>
                <!--列表-->
                <el-table
                    :data="variableList"
                    v-loading="listLoading"
                    style="width: 100%"
                    ref="table"
                    class="custom-tbl"
                >
                    <el-table-column prop="Id" label="ID" width="100" sortable>
                    </el-table-column>
                    <el-table-column prop="Name" label="变量名" width="">
                    </el-table-column>
                    <el-table-column prop="DeviceName" label="设备名称" width="">
                    </el-table-column>
                    <el-table-column prop="DeviceAddress" label="变量地址">
                    </el-table-column>
                    <el-table-column prop="DataType" label="数据类型">
                    </el-table-column>
                    <el-table-column prop="IsUpload" label="是否上传" width="100">
                        <template #default="scope">
                        <el-tag
                            :type="!scope.row.IsUpload ? 'success' : 'danger'"
                            disable-transitions
                            >{{ !scope.row.IsUpload ? "否" : "是" }}</el-tag
                        >
                        </template>
                    </el-table-column>

                    <el-table-column prop="Description" label="描述">
                        <template #default="scope">
                        <span v-html="scope.row.Description.substring(0, 100)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="CreateTime"
                        label="创建时间"
                        width="250"
                        sortable
                    >
                    </el-table-column>

                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                        <div v-for="item in operateButtons" v-bind:key="item.id">
                            <el-button link type="primary" size="small" @click="callFunction(item, scope.row)">{{item.name}}</el-button>
                        </div>
                        </template>
                    </el-table-column>
                </el-table>
                <!--工具条-->
                <el-col :span="18" class="toolbar">
                <el-pagination
                    layout="prev, pager, next"
                    @current-change="handleCurrentChange"
                    :page-size="6"
                    :total="total"
                    style="float: right"
                >
                </el-pagination>
                </el-col>
              </div>
              
          </el-card>

      </el-col>
  </el-row>
  <!--编辑界面-->
  <el-dialog
      :title="dialogTitle"
      v-model="editFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-input v-model="editForm.Id" auto-complete="off" v-show="false"></el-input>
        <el-form-item label="设备" prop="DeviceId">
          <el-select v-model="editForm.DeviceId" placeholder="请选择设备组">
            <el-option
              v-for="item in deviceList"
              :key="item.Id"
              :label="item.DeviceName"
              :value="item.Id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方法" prop="Method">
          <el-input v-model="editForm.Method" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="Index">
          <el-input v-model="editForm.Index" auto-complete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否上传" prop="IsUpload">
          <el-select v-model="editForm.IsUpload" placeholder="请选择">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="ProtectType">
          <el-select v-model="editForm.ProtectType" placeholder="请选择">
            <el-option
              v-for="item in protectTypes"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" prop="DataType">
          <el-select v-model="editForm.DataType" placeholder="请选择">
            <el-option
              v-for="item in DataTypes"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表达式" prop="Expressions">
          <el-input v-model="editForm.Expressions" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="别名" prop="Alias">
          <el-input v-model="editForm.Alias" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="Description">
          <el-input v-model="editForm.Description" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editCancel">取消</el-button>
          <el-button
            type="primary"
            @click.native="editSubmit(editFormRef)"
            :loading="editLoading"
            >提交</el-button
          >
        </div>
      </template>
    </el-dialog>
</section>
</template>

<script lang="ts" setup>
import { getDeviceGroupTree, getDeviceVariableList, getDeviceAll, editDeviceVariable } from "/@/api/device";
import {ref, onMounted, reactive, watch} from 'vue';
import { ElMessageBox, ElMessage, ElTree, FormInstance, FormRules} from 'element-plus'
import { getButtonMap } from "/@/router/backEnd";
import { useRoute } from 'vue-router';

interface Tree {
    label: string
    children?: Tree[]
}
const route = useRoute();
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const editFormRef = ref<FormInstance>()
const treeData = ref([]);
const deviceList = ref();
const variableList = ref();
const listLoading = ref(false);
const editLoading = ref(false);
const operateButtons = ref();
const buttonFuncs = ref({});
const total = ref(0);
const page = ref(1);
const dialogTitle = ref('编辑')
const editFormVisible = ref(false);
const editFormRules = reactive<FormRules<any>>({
  Name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  DeviceId: [{ required: true, message: '请选择设备', trigger: 'blur' }],
})
const statusList = [
    { value: 0, Name: '否' },
    { value: 1, Name: '是' },
]
const protectTypes = [
    { value: 0, Name: '只读' },
    { value: 1, Name: '读写' },
]
const DataTypes = [
    { value: 0, Name: 'Bit' },
    { value: 1, Name: 'Bool' },
    { value: 2, Name: 'UByte' },
    { value: 3, Name: 'Byte' },
    { value: 4, Name: 'Uint16' },
    { value: 5, Name: 'Int16' },
    { value: 6, Name: 'Bcd16' },
    { value: 7, Name: 'Uint32' },
    { value: 8, Name: 'int32' },
    { value: 9, Name: 'Float' },
    { value: 10, Name: 'Bcd32' },
    { value: 11, Name: 'Uint64' },
    { value: 12, Name: 'Int64' },
    { value: 13, Name: 'Double' },
    { value: 14, Name: 'Ascii字符串' },
    { value: 15, Name: 'Utf8字符串' },
    { value: 16, Name: '日期' },
    { value: 17, Name: '时间戳（毫秒）' },
    { value: 18, Name: '时间戳（秒）' },
    { value: 19, Name: 'Gb2312字符串' },
]
const editForm = ref({
    'Id': 0,
    'Name': '',
    'DeviceId': 0,
    'Method': '',
    'Index': 0,
    'IsUpload': 0,
    'ProtectType': 0,
    'DataType': 0,
    'Expressions': '',
    'Alias': '',
    'Description': '',
})
const filters = reactive({
    keyword: '',
    deviceId: 0,
})
const defaultProps = {
  children: 'Devices',
  label: 'Label',
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

const getDeviceTree = () => {
    getDeviceGroupTree({}).then((res) => {
      treeData.value = res.data;
    });
}
const handleCurrentChange = (val: number) => {
    page.value = val;
    getList();
}

const callFunction = (item: any, row: any) => {
    item.Func.call(this, row);
}

const handleAdd = () => {
    editFormVisible.value = true;
    dialogTitle.value = "新增"
    editForm.value = Object.assign({})
}

const handleEdit = (row: any) => {
    editFormVisible.value = true;
    dialogTitle.value = "编辑"
    editForm.value = Object.assign({}, row)
}

const editSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            ElMessageBox.confirm("确认提交吗？", "提示", {}).then(() => {
            editLoading.value = true;
            //NProgress.start();
            let para = Object.assign({}, editForm);

            editDeviceVariable(para).then((res) => {
                if (res.success) {
                    editLoading.value = false;
                    //NProgress.done();
                    ElMessage({
                        message: res.msg,
                        type: "success",
                    });
                    formEl.resetFields();
                    editFormVisible.value = false;
                    getList();
                } else {
                    ElMessage({
                        message: res.msg,
                        type: "error",
                    });
                }
            });
            });
        }
        });
}

const editCancel = () => {
    editFormVisible.value = false;
    editLoading.value = false;
}

const getList = () => {
    let para = {
        page: page,
        key: filters.keyword,
    };
    getDeviceVariableList(para).then((res) => {
        variableList.value = res.data;
        total.value = res.data.dataCount;
    });
}
  
onMounted(() => {
    let buttonMap = getButtonMap(route.path);
    buttonFuncs.value = buttonMap['buttonFuncs']|| [];
    operateButtons.value = buttonMap['operation'] || [];

  getDeviceTree();
  getDeviceAll({}).then((res) => {
    deviceList.value = res.data;
  })

})
</script>
<style>

  .text {
      font-size: 14px;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }

  .clearfix:after {
      clear: both
  }

  .box-card {
      width: 98%;
  }

</style>
